package com.easytouch.vmhdl.fragment;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

import com.easytouch.core.DriverThread;
import com.easytouch.core.model.GoodsModel;
import com.easytouch.core.utils.Log;
import com.easytouch.core.utils.Tools;
import com.easytouch.vmhdl.AppApplication;
import com.easytouch.vmhdl.R;
import com.easytouch.vmhdl.activity.MainActivity;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.ref.SoftReference;
import java.util.ArrayList;

/**
 * Created by gulin on 2017/12/1.
 */

public class ListFragment extends BaseFragment implements View.OnClickListener {

    private Log mLogger = new Log("ListFragment.txt");

    private GridView mGv_all_list;
    private Button mBtBack;

    private ArrayList<GoodsModel> mGoodsList = new ArrayList<>();
    MyAdapter myAdapter;

    private int mDuration = 60; // 倒计时

    private MyHandler mHandler;

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_list, container, false);

        hideTop();
        hideBottom();

        mGv_all_list = view.findViewById(R.id.gv_all_list);
        mBtBack = view.findViewById(R.id.bt_back);
        mBtBack.setOnClickListener(this);

        getAllGoods();
        myAdapter = new MyAdapter(getActivity());
        mGv_all_list.setAdapter(myAdapter);
        mGv_all_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if(position >= mGoodsList.size())
                {
                    return;
                }
                GoodsModel goods = mGoodsList.get(position);
                if(!goods.isGoodsHaveStock())
                {
                    return;
                }
                Bundle bundle = new Bundle();
                bundle.putString(PayFragment.PARAM_GOODS, goods.toString());
                goToFragment(MainActivity.FRAGMENT_PAY, bundle);
            }
        });

        mHandler = new MyHandler(this);
        mHandler.sendEmptyMessage(0);
        return view;
    }

    private void getAllGoods()
    {
        ArrayList<GoodsModel> goodsList = new ArrayList<>();
        //get all goods
        for(int i = 0;i < 5;i++) {
            String json = DriverThread.getInstance().getGoodsByCategory(i + 1, false);
            if(json == null || "".equals(json))
            {
                continue;
            }
            try {
                JSONObject object = new JSONObject(json);
                JSONArray data = object.getJSONArray("data");
                if(data == null || data.length() == 0)
                {
                    continue;
                }
                for (int j = 0;j < data.length();j++) {
                    JSONObject obj = data.getJSONObject(j);
                    GoodsModel model = GoodsModel.fromJson(obj);
                    goodsList.add(model);
                }
            } catch (JSONException e) {
                continue;
            }
        }
        //goodsList = goodsList.stream().filter(goods -> goods.getTemperatureState() == ColumnModel.TEMPERATURE_COLD).collect(Collectors.toList());
        mGoodsList.clear();
        int len = goodsList.size();
        if(len == 0)
        {
            return;
        }
        mGoodsList.addAll(goodsList);
    }

    public void setImage(ImageView imageView, String imageName) {

        mImageLoader.displayImage("file://" + AppApplication.path + "/images/goods_image/" + imageName, imageView, options, mLoadingListener);
    }

    @Override
    public void onDestroyView() {
        if(mHandler != null)
        {
            mHandler.removeMessages(0);
        }
        super.onDestroyView();
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        switch (id)
        {
            case R.id.bt_back:
                goToFragment(MainActivity.FRAGMENT_HOME, null);
                break;
        }
    }

    static class MyHandler extends Handler
    {

        private SoftReference<ListFragment> mFragment;

        public MyHandler(ListFragment fragment)
        {
            mFragment = new SoftReference<ListFragment>(fragment);
        }

        @Override
        public void handleMessage(Message msg)
        {
            super.handleMessage(msg);
            if(mFragment == null || mFragment.get() == null)
            {
                return;
            }
            switch (msg.what)
            {
                case 0: //倒计时
                {
                    int duration = mFragment.get().mDuration;
                    if(duration <= 0)
                    {
                        mFragment.get().goToFragment(MainActivity.FRAGMENT_HOME, null);
                    }
                    else
                    {
                        mFragment.get().mDuration--;
                        sendEmptyMessageDelayed(0, 1000);
                    }
                    break;
                }
            }
        }
    }

    class MyAdapter extends BaseAdapter {

        private ViewHolder holder;
        private Context mContext;

        public MyAdapter(Context context) {
            mContext = context;
        }

        @Override
        public int getCount() {
            return mGoodsList.size();
        }

        @Override
        public Object getItem(int i) {
            return mGoodsList.get(i);
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = View.inflate(mContext, R.layout.item_gridview, null);
                holder = new ViewHolder();
                holder.tv_price = convertView.findViewById(R.id.tv_price);
                holder.goods_image = convertView.findViewById(R.id.goods_image);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            final GoodsModel goods = mGoodsList.get(position);
            //商品图片
            setImage(holder.goods_image, String.valueOf(goods.getCode()) + "/0.png");
            //价格
            String price = Tools.priceFormat(String.valueOf(goods.getPrice()));
            holder.tv_price.setText(price);

            return convertView;
        }

        class ViewHolder {
            TextView tv_price;
            ImageView goods_image;
        }

    }
}
